// import 'dart:_http';

import 'package:exsun_plate_app/common/constant.dart';
import 'package:exsun_plate_app/mvp/model/get_code_entity.dart';
import 'package:exsun_plate_app/mvp/model/login_model.dart';
import 'package:exsun_plate_app/mvp/presenter/login_presenter.dart';
import 'package:exsun_plate_app/util/common_utils.dart';
import 'package:flutter/foundation.dart';
import 'package:flutter/material.dart';
import 'package:flutter/services.dart';
import 'package:flutter/widgets.dart';
import 'package:common_utils/common_utils.dart';
import 'package:exsun_plate_app/mvp/presenter/login_presenter_iml.dart';
import 'package:logger/logger.dart';
import 'package:shared_preferences/shared_preferences.dart';
import 'package:flutter_spinkit/flutter_spinkit.dart';

class LoginPage extends StatefulWidget {
  @override
  _LoginPageState createState() {
    _LoginPageState view = new _LoginPageState();
    LoginPresenterIml loginPresenterIml = LoginPresenterIml(view);
    loginPresenterIml.init();
    return view;
  }
}

enum CountDownState {
  Start, // 0
  Goon, // 1
  End, // 2
}

class _LoginPageState extends State<LoginPage>
    with WidgetsBindingObserver
    implements LoginView {
  GlobalKey<FormState> accountFormKey = new GlobalKey<FormState>();
  GlobalKey<FormState> phoneFormKey = new GlobalKey<FormState>();
  final _userNameController = TextEditingController();
  final _passwordController = TextEditingController();
  final _phoneController = TextEditingController();
  final _codeController = TextEditingController();
  final _loadingContainer = SpinKitFadingCircle(
    size: 60,
    itemBuilder: (_, int index) {
      return DecoratedBox(
        decoration: BoxDecoration(
          borderRadius: BorderRadius.circular(8),
          color: index.isEven ? Colors.blue : Colors.blue,
        ),
      );
    },
  );

  LoginPresenterIml _loginPresenterIml;
  var logger = Logger(
    printer: PrettyPrinter(),
  );
  String userName;
  String password;
  String phone;
  String code;
  int checkedId = 0;
  TimerUtil _timerUtil;
  int _count = 0;
  int totalSecond = 60;
  bool _showLoading = false;
  CountDownState _status = CountDownState.Start;
  static final String startCodeText = '获取验证码';
  static final String getCodeAgain = '重新获取';
  String codeText = startCodeText;
  FocusNode _useNameFocusNode = FocusNode();
  FocusNode _passwordFocusNode = FocusNode();
  FocusNode _phoneFocusNode = FocusNode();
  FocusNode _codeFocusNode = FocusNode();

  BuildContext _context;
  final String accountKey = "accountKey";

  final String mobileKey = "mobileKey";
  final List<Tab> myTabs = <Tab>[
    Tab(
      text: '账号登录',
    ),
    Tab(
      text: '手机号登录',
    ),
  ];

  final SystemUiOverlayStyle _style = SystemUiOverlayStyle(
      statusBarColor: Colors.transparent, statusBarBrightness: Brightness.dark);

  void login() {
    if (_userNameController.text.length == 0) {
      CommonUtils.showToast(_context, '请输入用户名');
      return;
    }
    if (_passwordController.text.length == 0) {
      CommonUtils.showToast(_context, '请输入密码');
      return;
    }

    var loginForm = accountFormKey.currentState;

    if (loginForm.validate()) {
      loginForm.save();
      setState(() {
        _showLoading = true;
      });
      _loginPresenterIml.login(userName, password);
    }
  }

  // void doLogin(String userName,String password){
  //   HttpClient httpClient = new HttpClient();
  // }

  void checkPhone() {
    var phoneForm = phoneFormKey.currentState;
    if (phoneForm.validate()) {
      phoneForm.save();
      setState(() {
        _showLoading = true;
      });
      print('phone:  ' + phone + '  code:  ' + code);
    }
  }

  //点击获取验证码后开始倒计时，并改变控件显示为时间的秒数
  void _doCountDown() {
    if (_phoneController.text.length == 0) {
      CommonUtils.showToast(_context, '请输入手机号');
      return;
    }
    var isPhone = CommonUtils.isPhone(_phoneController.text);
    if (!isPhone) {
      CommonUtils.showToast(_context, '请输入正确的手机号');
      return;
    }
    //如果已经在倒计时返回
    if (_status == CountDownState.Goon) {
      return;
    }
    setState(() {
      _status = CountDownState.Goon;
    });
    _loginPresenterIml.getCode(_phoneController.text);

    _timerUtil = new TimerUtil(mTotalTime: totalSecond * 1000);
    _timerUtil.setOnTimerTickCallback((int tick) {
      int _tick = tick ~/ 1000;
      setState(() {
        _count = _tick.toInt();
      });
      if (_tick == 0) {
        codeText = getCodeAgain;
        setState(() {
          _status = CountDownState.End;
        });
      } else {
        codeText = '$_tick秒';
        setState(() {
          _status = CountDownState.Goon;
        });
      }
    });
    _timerUtil.startCountDown();
  }

  @override
  void initState() {
    super.initState();
    WidgetsBinding.instance.addObserver(this); //添加观察者
    _useNameFocusNode.addListener(() {
      setState(() {});
    });
    _passwordFocusNode.addListener(() {
      setState(() {});
    });
    _phoneFocusNode.addListener(() {
      setState(() {});
    });
    _codeFocusNode.addListener(() {
      setState(() {});
    });
  }

  _onAccountTab() {
    checkedId = 0;
    setState(() {});
  }

  _onPhoneTab() {
    checkedId = 1;
    setState(() {
      if (_timerUtil != null) {
        _timerUtil.cancel();
        codeText = startCodeText;
      }
      _status = CountDownState.Start;
    });
  }

  @override
  void didChangeAppLifecycleState(AppLifecycleState state) {
    super.didChangeAppLifecycleState(state);
    print("lifeChanged $state");
  }

  @override
  Widget build(BuildContext context) {
    //将style设置到app
    _context = context;
//    if (defaultTargetPlatform==TargetPlatform.android) {
    SystemChrome.setSystemUIOverlayStyle(_style);
//    }else if (defaultTargetPlatform==TargetPlatform.iOS) {
//      SystemChrome.setSystemUIOverlayStyle(SystemUiOverlayStyle.dark);
//    }
    var headImageAndText = Container(
      margin: EdgeInsets.fromLTRB(0, 64, 0, 0),
      child: new Column(children: <Widget>[
        new Image.asset('images/login_logo.png'),
        new Text(
          '依迅手机查车',
          style: TextStyle(fontSize: 18.0),
        ),
      ]),
    );

    var chooseLoginWidget = new Container(
      margin: EdgeInsets.fromLTRB(30, 80, 30, 0),
      child: new Center(
        child: new Row(
          children: <Widget>[
            new Expanded(
                child: new GestureDetector(
              child: new Column(
                children: <Widget>[
                  new Text(myTabs[0].text,
                      textAlign: TextAlign.center,
                      style: TextStyle(
                        color: checkedId == 0
                            ? Constants.mainGreenColor
                            : Constants.descriptionTextColor,
                      )),
                  new Container(
                    key: new Key(accountKey),
                    margin: EdgeInsets.fromLTRB(0, 5, 0, 0),
                    color: checkedId == 0
                        ? Constants.mainGreenColor
                        : Colors.transparent,
                    width: 55,
                    height: 2,
                  )
                ],
              ),
              onTap: _onAccountTab,
            )),
            new Expanded(
                child: new GestureDetector(
              child: new Column(
                children: <Widget>[
                  new Text(
                    myTabs[1].text,
                    textAlign: TextAlign.center,
                    style: TextStyle(
                      color: checkedId == 1
                          ? Constants.mainGreenColor
                          : Constants.descriptionTextColor,
                    ),
                  ),
                  new Container(
                    key: new Key(accountKey),
                    margin: EdgeInsets.fromLTRB(0, 5, 0, 0),
                    color: checkedId == 1
                        ? Constants.mainGreenColor
                        : Colors.transparent,
                    width: 70,
                    height: 2,
                  )
                ],
              ),
              onTap: _onPhoneTab,
            )),
          ],
        ),
      ),
    );

    var accountLoginWidget = new Container(
      margin: EdgeInsets.fromLTRB(20, 20, 20, 0),
      padding: const EdgeInsets.all(16.0),
      child: new Form(
          key: accountFormKey,
          child: new Column(
            children: <Widget>[
              new Container(
                height: 50,
                alignment: Alignment.center,
                decoration:
                    BoxDecoration(shape: BoxShape.rectangle, boxShadow: [
                  BoxShadow(
                    color: Constants.blueShadowColor,
                    blurRadius: 5.0,
                    spreadRadius: 5.0,
                    offset: Offset(-1.0, 1.0),
                  ),
                ]),
                child: new TextFormField(
                  focusNode: _useNameFocusNode,
                  decoration: new InputDecoration(
                      fillColor: Colors.white,
                      filled: true,
                      //这个属性可以控制hintText垂直局中
                      contentPadding:
                          const EdgeInsets.symmetric(vertical: 10.0),
                      prefixIcon: _useNameFocusNode.hasFocus
                          ? Image.asset('images/login_usr_number_s.png')
                          : Image.asset('images/login_usr_number_n.png'),
                      border: OutlineInputBorder(
                          borderRadius: BorderRadius.circular(5),
                          borderSide: BorderSide.none),
                      hintText: '请输入用户名',
                      hintStyle: TextStyle(fontSize: 12)),
                  onSaved: (value) {
                    userName = value;
                  },
                  textInputAction: TextInputAction.next,
                  onFieldSubmitted: (value) {},
                  controller: _userNameController,
                ),
              ),
              new Container(
                height: 50,
                margin: EdgeInsets.fromLTRB(0, 30, 0, 0),
                alignment: Alignment.center,
                decoration:
                    BoxDecoration(shape: BoxShape.rectangle, boxShadow: [
                  BoxShadow(
                    color: Constants.blueShadowColor,
                    blurRadius: 5.0,
                    spreadRadius: 5.0,
                    offset: Offset(-1.0, 1.0),
                  ),
                ]),
                child: new TextFormField(
                  focusNode: _passwordFocusNode,
                  decoration: new InputDecoration(
                      fillColor: Colors.white,
                      filled: true,
                      //这个属性可以控制hintText垂直局中
                      contentPadding:
                          const EdgeInsets.symmetric(vertical: 10.0),
                      prefixIcon: _passwordFocusNode.hasFocus
                          ? Image.asset('images/login_password_s.png')
                          : Image.asset('images/login_password_n.png'),
                      border: OutlineInputBorder(
                          borderRadius: BorderRadius.circular(5),
                          borderSide: BorderSide.none),
                      hintText: '请输入密码',
//                      labelText: 'Password',
                      hintStyle: TextStyle(fontSize: 12)),
                  //是否是密码
                  obscureText: true,
                  onSaved: (value) {
                    password = value;
                  },
                  textInputAction: TextInputAction.done,
                  controller: _passwordController,
                ),
              ),
            ],
          )),
    );

    var phoneLoginWidget = new Container(
      margin: EdgeInsets.fromLTRB(20, 20, 20, 0),
      padding: const EdgeInsets.all(16.0),
      child: new Form(
          key: phoneFormKey,
          child: new Column(
            children: <Widget>[
              new Container(
                height: 50,
                alignment: Alignment.center,
                decoration:
                    BoxDecoration(shape: BoxShape.rectangle, boxShadow: [
                  BoxShadow(
                    color: Constants.blueShadowColor,
                    blurRadius: 5.0,
                    spreadRadius: 5.0,
                    offset: Offset(-1.0, 1.0),
                  ),
                ]),
                child: new TextFormField(
                  focusNode: _phoneFocusNode,
                  decoration: new InputDecoration(
                      fillColor: Colors.white,
                      filled: true,
                      //这个属性可以控制hintText垂直局中
                      contentPadding:
                          const EdgeInsets.symmetric(vertical: 10.0),
                      prefixIcon: _phoneFocusNode.hasFocus
                          ? Image.asset('images/login_cell_phone_number_s.png')
                          : Image.asset('images/login_cell_phone_number_n.png'),
                      border: OutlineInputBorder(
                          borderRadius: BorderRadius.circular(5),
                          borderSide: BorderSide.none),
                      hintText: '请输入手机号',
                      hintStyle: TextStyle(fontSize: 12)),
                  validator: (value) {
                    phone = value;
                    if (value.length == 0) {
                      CommonUtils.showToast(context, '请输入手机号');
                    }
                    if (!CommonUtils.isPhone(value)) {
                      CommonUtils.showToast(context, '请输入正确的手机号');
                    }
                  },
                  inputFormatters: <TextInputFormatter>[
                    WhitelistingTextInputFormatter.digitsOnly, //只输入数字
                  ],
                  onSaved: (value) {
                    phone = value;
                  },
                  textInputAction: TextInputAction.next,
                  controller: _phoneController,
                ),
              ),
              new Container(
                  height: 50,
                  margin: EdgeInsets.fromLTRB(0, 30, 0, 0),
                  alignment: Alignment.center,
                  decoration:
                      BoxDecoration(shape: BoxShape.rectangle, boxShadow: [
                    BoxShadow(
                      color: Constants.blueShadowColor,
                      blurRadius: 5.0,
                      spreadRadius: 5.0,
                      offset: Offset(-1.0, 1.0),
                    ),
                  ]),
                  child: new Container(
                    decoration: BoxDecoration(
                      color: Colors.white,
                      borderRadius: BorderRadius.all(
                        Radius.circular(5.0),
                      ),
                    ),
                    child: new Row(
                      children: <Widget>[
                        new Expanded(
                          child: GestureDetector(
                            child: TextFormField(
                              decoration: new InputDecoration(
                                  fillColor: Colors.white,
                                  filled: true,
                                  //这个属性可以控制hintText垂直局中
                                  contentPadding: const EdgeInsets.symmetric(
                                      vertical: 10.0),
                                  prefixIcon: _codeFocusNode.hasFocus
                                      ? Image.asset(
                                          'images/login_verification_code_s.png')
                                      : Image.asset(
                                          'images/login_verification_code_n.png'),
                                  border: OutlineInputBorder(
                                      borderRadius: BorderRadius.circular(5),
                                      borderSide: BorderSide.none),
                                  hintText: '请输入验证码',
                                  hintStyle: TextStyle(fontSize: 12)),
                              onSaved: (value) {
                                code = value;
                              },
                              focusNode: _codeFocusNode,
                              controller: _codeController,
                              textInputAction: TextInputAction.done,
                            ),
                            onTap: _doCountDown,
                          ),
                        ),
                        new Container(
                          margin: EdgeInsets.fromLTRB(20, 0, 5, 0),
                          height: 25,
                          width: 1.5,
                          color: Constants.divideLineColor,
                        ),
                        new Container(
                          width: 80.0,
                          margin: EdgeInsets.fromLTRB(5, 0, 20, 0),
                          child: new GestureDetector(
                              onTap: () {
                                _doCountDown();
                              },
                              child: new Center(
                                child: new Text(
                                  codeText,
                                  style: TextStyle(
                                    color: Constants.mainBlueColor,
                                  ),
                                ),
                              )),
                        )
                      ],
                    ),
                  )),
            ],
          )),
    );

    var loginButtonWidget = new Container(
      margin: EdgeInsets.fromLTRB(36, 30, 36, 0),
      child: new SizedBox(
        width: 340.0,
        height: 45.0,
        child: new RaisedButton(
          onPressed: checkedId == 0 ? login : checkPhone,
          child: new Text(
            '登录',
            style: TextStyle(fontSize: 18.0),
          ),
        ),
      ),
    );

    return GestureDetector(
      onTap: () {
        FocusScope.of(context).requestFocus(FocusNode());
      },
      child: Scaffold(
          appBar: PreferredSize(
              child: AppBar(
                backgroundColor: Colors.transparent,
                elevation: 0,
                brightness: Brightness.light,
              ),
              preferredSize: Size.fromHeight(0)),
//        new AppBar(
//          backgroundColor: Colors.transparent,
//          elevation: 0,
//          brightness: Brightness.light,
//        ),
          body: new SingleChildScrollView(
              child: new ConstrainedBox(
            constraints: new BoxConstraints(
              minHeight: 120.0,
            ),
            child: new Column(
              children: <Widget>[
                headImageAndText,
                chooseLoginWidget,
                checkedId == 0 ? accountLoginWidget : phoneLoginWidget,
                loginButtonWidget,
                new Container(
                    child: _showLoading ? _loadingContainer : Text("")),
              ],
            ),
          ))),
    );
  }

  @override
  onLoginFail(String errorMsg) {
    CommonUtils.showToast(context, errorMsg);
    setState(() {
      _showLoading = false;
    });
  }

  @override
  onLoginSuccess(LoginModel model) {
    if (!mounted) {
      return;
    }
    setState(() {
      _showLoading = false;
      if (model.code == Constants.httpOK) {
        LoginModelDetail detail = model.detail;
        print(detail.toJson());
        _saveInfoJumpMainPage(detail);
      } else {
        onLoginFail(model.msg);
      }
    });
  }

  @override
  setPresenter(LoginPresenter presenter) {
    _loginPresenterIml = presenter;
  }

  Future _saveInfoJumpMainPage(LoginModelDetail detail) async {
    SharedPreferences prefs = await SharedPreferences.getInstance();
    await prefs.setString(Constants.USER_NAME_KEY, detail.name);
    await prefs.setBool(Constants.IS_LOGIN, true);
    await Navigator.of(context).pushReplacementNamed('/HomePage');
  }

  @override
  onCodeFail(String errorMsg) {
    CommonUtils.showToast(context, errorMsg);
  }

  @override
  onCodeSuccess(GetCodeEntity model) {
    if (!mounted) {
      return;
    }
    CommonUtils.showToast(context, model.msg);
    setState(() {
      _showLoading = false;
      if (model.code == Constants.httpOK) {
        var detail = model.detail;
        print(detail);
      } else {
        onCodeFail(model.msg);
      }
    });
  }
}
